package open.douban.hashtree;

import java.io.IOException;

/**
 *
 */
public class HashTreeInArray extends HashTree {

	private Node[] tree = null;

	public HashTreeInArray(String path) throws IOException {
		// take it easy, can not use template method pattern for this
		// Do not call sub-class method in parent constructor for the object in
		// sub-class is not
		// constructed.
		super(path, false);

		init();
		build();
	}

	@Override
	protected void init() {
		tree = new Node[g_index[height + 1]];
	}

	@Override
	protected void enlarge() {
		Node[] temp = new Node[g_index[height + 1]];
//		System.out.println(temp.length + " " + tree.length);
		System.arraycopy(tree, 0, temp, 0, tree.length);
		tree = temp;
		root = tree[0];
	}

	@Override
	protected Node node(int id) {
		return tree[id];
	}

	@Override
	protected void node(int id, Node n) {
		tree[id] = n;
	}

	@Override
	protected void remove(int id) {
		tree[id] = null;
	}

	@Override
	public BSTIterator iterator() {
		BSTIterator it = new BSTIterator() {
			int cursor = 0;
			int end = tree.length;

			@Override
			public boolean hasNext() {
				return cursor < end;
			}

			@Override
			public Node next() {
				return tree[cursor++];
			}

		};
		return it;
	}

	@Override
	public int getNodeNumber() {
		return tree.length;
	}
}
